package org.dromara.web.service;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * 微信小程序API工具类
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class WeiXinService {

    private static WebClient webClient;

    private void setWebClient(){
        if(webClient == null){
            webClient = WebClient.builder().baseUrl("https://api.weixin.qq.com").build();
        }
    }

    /**
     * 小程序登录
     * @param code
     * @param client
     * @return
     */
    public JSONObject weixinCode2Session(String code, SysClient client) {
        setWebClient();
        // 发送GET请求到/sns/jscode2session 端点
        String response = webClient.get()
            .uri("/sns/jscode2session?appid="+client.getClientKey()+"&secret="+client.getClientSecret()+"&js_code="+code+"&grant_type=authorization_code")
            .retrieve()
            .bodyToMono(String.class)
            .block(); // 使用block()阻塞并等待结果
        return JSONObject.parseObject(response);
    }

    /**
     * 获取接口调用凭据
     * @param client
     * @return
     */
    public JSONObject getToken(SysClient client) {
        setWebClient();
        // 发送GET请求到/sns/jscode2session 端点
        String response = webClient.get()
            .uri("/cgi-bin/token?grant_type=client_credential&appid="+client.getClientKey()+"&secret="+client.getClientSecret())
            .retrieve()
            .bodyToMono(String.class)
            .block(); // 使用block()阻塞并等待结果
        return JSONObject.parseObject(response);
    }

    /**
     * 获取手机号码
     * @param code
     * @param access_token
     * @param client
     * @return
     */
    public JSONObject getuserphonenumber(String code,String access_token, SysClient client) {
        setWebClient();
        // 发送GET请求到/sns/jscode2session 端点
        String response = webClient.post()
            .uri("/wxa/business/getuserphonenumber?access_token="+access_token)
            .contentType(MediaType.APPLICATION_JSON) // 设置请求的内容类型
            .bodyValue(new cn.hutool.json.JSONObject("{\"code\":\""+code+"\"}"))
            .retrieve()
            .bodyToMono(String.class)
            .block(); // 使用block()阻塞并等待结果
        return JSONObject.parseObject(response);
    }
}
